package test;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import javax.swing.SwingWorker;
import javax.swing.event.EventListenerList;

import MVC.Exceptions.CPException;
import MVC.events.ResultArrivedEvent;
import MVC.events.TextChangedEvent;
import MVC.listeners.ReturnListener;
import MVC.listeners.TextListener;

public class RunCheckers  extends SwingWorker<Result,Void>{

	private ArrayList<String> testsToRun = null; 
	private ArrayList<Integer> methodToTest = null;
	private EventListenerList textListeners;
	private EventListenerList returnListeners;
	
	public RunCheckers(ArrayList<String> testsToRun,ArrayList<Integer> IDs, TextListener Tlistener,ReturnListener Rlistener) throws CPException{
		this.textListeners = new EventListenerList();
		addTextListeners(Tlistener);
		this.returnListeners = new EventListenerList();
		addReturnListeners(Rlistener);
		this.methodToTest = IDs;
		if (testsToRun.size() != 0){
			this.testsToRun = testsToRun;
		}else{
			throw new CPException("Please select a test");
		}
	}
	
	

	//AddListeners
	public void addReturnListeners(ReturnListener rlistener){
		this.returnListeners.add(ReturnListener.class, rlistener);
	}
	
	public void addTextListeners(TextListener listener){
		this.textListeners.add(TextListener.class, listener);
	}

	//Fire
	public void fireTextListeners(String text){
		TextListener[] textList = (TextListener[])this.textListeners.getListeners(TextListener.class);
		
		for(TextListener listener : textList){
			listener.TextChanged(new TextChangedEvent(this, text));
		}
	}
	
	public void fireReturnListeners(Result r){
		ReturnListener[] returnList = (ReturnListener[])this.returnListeners.getListeners(ReturnListener.class);
		for(ReturnListener listener : returnList){
			listener.ReturnArrived(new ResultArrivedEvent(this, r));
		}
	}
	
	

	@Override
	protected Result doInBackground() throws Exception {
		Result res = new Result(this.methodToTest);
		for (Integer id : this.methodToTest){
			for (String testType : this.testsToRun){
				try {
					res.addMR(PatternFinderFactory.create(testType,id).executeCheckPattern());
					fireTextListeners("check method : "+id+" done");
				} catch (CPException e) {
					e.printStackTrace();
				}
			}
		}
		return res;
	}
	
	@Override
	protected void done() {
		try {
			fireReturnListeners(get());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
